package com.wanpinghui.supplier.object;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseFragment;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.object.adapter.ObjectListAdapter;
import com.wanpinghui.supplier.user.BusinessTypeActivity;
import com.wanpinghui.supplier.user.SelectCityActivity;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.object.ObjectService;
import com.wanpinghui.wphlibrary.model.object.bean.ObjectDetailBean;
import com.yunshl.yunshllibrary.recyclerview.OnItemClickListener;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/23
 ***/
@ContentView(R.layout.layout_fragment_object)
public class ObjectFragment extends BaseFragment {
    private static final int BUSINESSTYPE = 111;
    private static final int SELECT_CITY = 112;
    private static final int REQUEST_DETAIL = 113;
    @ViewInject(R.id.iv_filter)
    private ImageView mImageViewFilter;
    @ViewInject(R.id.recv_object_list)
    private SuperRecyclerView mRecyclerViewList;
    @ViewInject(R.id.ll_empty_view)
    private LinearLayout mLayoutEmptyView;
    @ViewInject(R.id.tv_empty_tip)
    private TextView mTextViewEmptyTip;
    @ViewInject(R.id.tv_see_my)
    private TextView mTextViewSeeMy;

    private long sortVal;
    private ObjectListAdapter mAdapter;

    private String cityFilter = "all";
    private String businessFilter = "all";
    private String demandFilter = "all";
    private FilterManager filterManager;
    private SwipeRefreshLayout.OnRefreshListener refreshListener;
    private long lastPublistTime;//最新一条项目的发布时间
    private int uploadCount;
    private boolean isVisible;

    @Override
    public void init() {
        mAdapter = new ObjectListAdapter(getActivity());
        mRecyclerViewList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewList.setAdapter(mAdapter);
        filterManager = new FilterManager(getActivity());
        bindEvents();
        refreshListener.onRefresh();
    }

    private void bindEvents() {
        filterManager.setSelectListener(new FilterManager.OnSelectListener() {
            @Override
            public void myAtten(String value) {
                cityFilter = value;
                reflash();
            }

            @Override
            public void myAttenType(String value) {
                businessFilter = value;
                reflash();
            }

            @Override
            public void orderType(String value) {
                demandFilter = value;
                reflash();
            }

            @Override
            public void setMyAttenType() {
                Intent intentType = new Intent(getActivity(), BusinessTypeActivity.class);
                startActivityForResult(intentType, BUSINESSTYPE);
            }

            @Override
            public void selectCity() {
                Intent intent = new Intent(getActivity(), SelectCityActivity.class);
                startActivityForResult(intent, SELECT_CITY);
            }

            @Override
            public void setMyCity() {

            }
        });
        mImageViewFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null) {
                    if (LoginUtil.loginFilter(getActivity())) {
                        filterManager.showFilter(getActivity().findViewById(R.id.root_view));
                    }
                }
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), ObjectDetailActivity.class);
                intent.putExtra("id", mAdapter.getDemandId(position));
                intent.putExtra("position", position);
                mAdapter.readObject(mAdapter.getDemandId(position));
                startActivityForResult(intent, REQUEST_DETAIL);
            }
        });

        refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                sortVal = 0;
                getData(sortVal);
            }
        };

        mRecyclerViewList.setRefreshListener(refreshListener);

        mTextViewSeeMy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cityFilter = "mine";
                businessFilter = "mine";
                demandFilter = "all";
                getData(sortVal);
            }
        });
    }

    private void getData(long sortVal) {
        WPHSdk.getService(ObjectService.class)
                .getObjectList(sortVal, cityFilter, businessFilter, demandFilter, new YRequestCallback<List<ObjectDetailBean>>() {
                    @Override
                    public void onSuccess(List<ObjectDetailBean> var1) {
                        setData(var1);
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        mRecyclerViewList.setRefreshing(false);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        mRecyclerViewList.setRefreshing(false);
                        var1.printStackTrace();
                    }
                });
    }

    private void setData(List<ObjectDetailBean> var1) {
        mRecyclerViewList.setRefreshing(false);
        uploadCount = 0;
        if (var1 != null && var1.size() > 0) {
            for (ObjectDetailBean objectDetailBean : var1) {
                if (objectDetailBean.getDemand().getPublished_at() > lastPublistTime) {
                    uploadCount++;
                }
            }
            lastPublistTime = var1.get(0).getDemand().getPublished_at();
        }
        if (getActivity() != null && isVisible) {
            ((HomePageActivity) getActivity()).showUpdateCount(uploadCount);
        }
        if (var1 == null || var1.size() < 20) {
            mRecyclerViewList.removeMoreListener();
            mRecyclerViewList.hideMoreProgress();
        } else {
            mRecyclerViewList.setupMoreListener(new OnMoreListener() {
                @Override
                public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                    sortVal = mAdapter.getLastPublistAdd();
                    getData(sortVal);
                }
            }, 1);
        }
        if (sortVal == 0) {
            mAdapter.setDatas(var1);
        } else {
            if (var1 != null && var1.size() > 0) {
                mAdapter.addDatas(var1);
            }
        }
        if (mAdapter.getItemCount() > 0) {
            mLayoutEmptyView.setVisibility(View.GONE);
        } else {
            mLayoutEmptyView.setVisibility(View.VISIBLE);
            if (isHaveFilter()) {
                mTextViewEmptyTip.setText("暂未找到您需要的订单信息");
                mTextViewSeeMy.setVisibility(View.VISIBLE);
            } else {
                mTextViewSeeMy.setVisibility(View.GONE);
                mTextViewEmptyTip.setText("无订单信息");
            }
        }
    }

    public boolean isHaveFilter() {
        if (TextUtil.isNotEmpty(cityFilter) && !cityFilter.equals("all")) {
            return true;
        } else if (TextUtil.isNotEmpty(businessFilter) && !businessFilter.equals("all")) {
            return true;
        } else if (TextUtil.isNotEmpty(demandFilter) && !demandFilter.equals("all")) {
            return true;
        }
        return false;
    }

    private void reflash() {

        if (mRecyclerViewList != null) {
            mRecyclerViewList.getSwipeToRefresh().post(new Runnable() {
                @Override
                public void run() {
                    mRecyclerViewList.setRefreshing(true);//执行下拉刷新的动画
                    refreshListener.onRefresh();//执行数据加载操作
                }
            });
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (isVisibleToUser) {
            if (mAdapter != null && mAdapter.getItemCount() > 0) {
                lastPublistTime = mAdapter.getData(0).getDemand().getPublished_at();
            }
            if (getActivity() != null) {
                reflash();
            }
        } else {
            if (getActivity() != null) {
                ((HomePageActivity) getActivity()).showWarningText("");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BUSINESSTYPE && resultCode == Activity.RESULT_OK) {
            businessFilter = "mine";
            reflash();
        } else if (requestCode == SELECT_CITY && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                cityFilter = data.getStringExtra("city");
                if (TextUtil.isEmpty(businessFilter)) {
                    cityFilter = "all";
                } else {
                    reflash();
                }
            }
        } else if (requestCode == REQUEST_DETAIL && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String dataStr = data.getStringExtra("result");
                int position = data.getIntExtra("position", -1);
                if (TextUtil.isNotEmpty(dataStr)) {
                    ObjectDetailBean objectDetailBean = new Gson().fromJson(dataStr, new TypeToken<ObjectDetailBean>() {
                    }.getType());
                    if (position >= 0) {
                        mAdapter.setData(position, objectDetailBean);
                    }
                }
            }
        }
    }

    public void setNewestTime(long time) {
        if (mAdapter != null && mAdapter.getItemCount() > 0) {
            lastPublistTime = mAdapter.getData(0).getDemand().getPublished_at();
        } else {
            lastPublistTime = time / 1000;
        }
    }
}
